import raf from 'rc-util/lib/raf';
import type React from 'react';
import { useEffect, useRef, useState } from 'react';
import type { TabOffset } from '../interface';

export type GetIndicatorSize = number | ((origin: number) => number);

export type UseIndicator = (options: {
  activeTabOffset?: TabOffset;
  horizontal: boolean;
}) => {
  style: React.CSSProperties | undefined;
};

const useIndicator: UseIndicator = ({ activeTabOffset, horizontal }) => {
  const [inkStyle, setInkStyle] = useState<React.CSSProperties>();
  const inkBarRafRef = useRef<number>();

  // Delay set ink style to avoid remove tab blink
  function cleanInkBarRaf() {
    raf.cancel(inkBarRafRef.current!);
  }

  useEffect(() => {
    const newInkStyle: React.CSSProperties = {};
    // console.log('--useIndicator--activeTabOffset--:', activeTabOffset);
    if (activeTabOffset) {
      if (horizontal) {
        newInkStyle.left = activeTabOffset.left + activeTabOffset.width / 2;
        newInkStyle.transform = 'translateX(-50%)';
        // newInkStyle.left = activeTabOffset.left;
        newInkStyle.width = activeTabOffset.width;
      }
    }

    cleanInkBarRaf();
    inkBarRafRef.current = raf(() => {
      setInkStyle(newInkStyle);
    });

    return cleanInkBarRaf;
  }, [activeTabOffset, horizontal]);

  return {
    style: inkStyle,
  };
};

export default useIndicator;
